import React, { Component } from 'react';
import { Icon, Button, List, Toast } from 'antd-mobile';
import router from 'umi/router';
import MyNavBar from 'components/navbar';
import { getIsDingTalk, dingCloseWindow } from 'utils/utils';
import commonStyles from 'utils/common.less';
import styles from './index.less';
import { MyIcon } from 'components/my-icon';
import { connect } from 'dva';
import { ENTER_TYPE, PROCESS_STATUS, AUTHENTICATION_FAIL_CODE, COUNT_DOWN, SERVICE_TYPE, AUTHENTICATION_REULST } from 'utils/Enum'
@connect(({ signCertificationResultsModel, pdfModel, sealAndSignatureModel }) => ({ signCertificationResultsModel, pdfModel, sealAndSignatureModel }))
class AuthenticationSuccess extends Component {
  constructor(props) {
    super(props);
    this.state = {}
  }
  async componentDidMount() {
    let { dispatch } = this.props
    await dispatch({
      type: 'signCertificationResultsModel/countDown',
      payload: COUNT_DOWN.RESULT_TIME
    })
    /**
     * 1. 如果是支付宝才需要设置session 当组件加载完成 设置session
     * 2. 判断是哪个请求
     * 3. 如果是支付宝就去请求结果 如果是手机直接开始倒计时
     */
    let { signCertificationResultsModel: { Certification, session, bizNo, userWsid, returnUrl, enterType, envelopeWsid, participantWsid, status, haveToAlipay } } = this.props;
    if (bizNo) {
      localStorage.setItem('haveToAlipay', haveToAlipay)
      localStorage.setItem('Contact', bizNo)
      localStorage.setItem("userWsid", userWsid)
      localStorage.setItem("Session", session)
      localStorage.setItem('returnUrl', unescape(returnUrl))
      localStorage.setItem('enterType', enterType)
      if (envelopeWsid !== '') {
        localStorage.setItem('envelopeWsid', envelopeWsid)
      }
      if (participantWsid !== '') {
        localStorage.setItem('participantWsid', participantWsid)
      }
      //查询中就显示loading动画
      this.getAlipayStatus(bizNo, userWsid, Certification)
    } else {
      switch (Number(status)) {
        case PROCESS_STATUS.PUSR_AUTHORIZING_SUCCESS:
          Toast.loading('签署中，请稍等', 0)
          this.getFormsAndSubmitConfirm()
          break;
        default:
          this.countDown()
          break;
      }

    }
  }

  countDown = async () => {
    //开始倒计时表示查询的结果已经返回 就消除loading动画
    this.timer = setInterval(async () => {
      let { signCertificationResultsModel: { count }, dispatch } = this.props
      count = count - 1
      if (count < 0) {
        this.goBack()
      } else {
        await dispatch({
          type: 'signCertificationResultsModel/countDown',
          payload: count
        })
      }
    }, 1000)
  }

  getAlipayStatus = (bizNo, userWsid, Certification) => {
    const { dispatch } = this.props
    switch (Number(Certification)) {
      case PROCESS_STATUS.UNKOWN_PAUTHORIZING_APPLY:
      case PROCESS_STATUS.UNKOWN_EAUTHORIZING_APPLY:
        dispatch({
          type: "signCertificationResultsModel/getAlipayDetail",
          payload: {
            userPersonWsid: userWsid,
            bizNo,
            serviceName: SERVICE_TYPE.CONFIRM_AUTH
          },
          callback: () => {
            const { signCertificationResultsModel: { isSuccess } } = this.props
            if (isSuccess) {
              // Toast.loading('签署中，请稍等', 0)
              this.getFormsAndSubmitConfirm()
              return
            }
            Toast.hide()
            this.countDown()
          }
        })
        break;
      case PROCESS_STATUS.UNKOWN_WISH_APPLY:
        dispatch({
          type: "signCertificationResultsModel/getIntendCertificationResult",
          payload: {
            bizNo,
            serviceName: SERVICE_TYPE.CONFIRM_AUTH
          },
          callback: () => {
            const { signCertificationResultsModel: { isSuccess } } = this.props
            if (isSuccess) {
              Toast.loading('签署中，请稍等', 0)
              this.getFormsAndSubmitConfirm()
              return
            }
            Toast.hide()
            this.countDown()
          }
        })
        break;
      default:
        break;
    }

  }

  getFormsAndSubmitConfirm = () => {//意愿认证成功后请求签署确认并跳转成功页面
    const { dispatch } = this.props;
    const envelopeWsid = localStorage.getItem('envelopeWsid');
    let participantWsid = localStorage.getItem('participantWsid');//参与签署方分配的ID
    dispatch({
      type: 'sealAndSignatureModel/getFormsSearch',
      payload: {
        envelopeWsid: envelopeWsid,
        participantWsid: participantWsid,
        query: {
          fields: null,
          filters: null,
          sorts: null,
          offset: 0,
          limit: 1000,
        },
      },
      callback: (res) => {
        if (res.length !== 0) {//获取当前的表单数据不为空
          const { dispatch } = this.props;
          const envelopeWsid = localStorage.getItem('envelopeWsid');
          let participantWsid = localStorage.getItem('participantWsid');//参与签署方分配的ID
          let signFormsWsid = [];
          res.forEach((item) => {
            signFormsWsid.push({
              formWsid: item.formWsid,
            });
          });
          dispatch({
            type: 'sealAndSignatureModel/submitConfirm',
            payload: {
              envelopeWsid: envelopeWsid,
              participantWsid: participantWsid,
              formsWsidData: {
                signForms: [...signFormsWsid]
              }
            },
            callback: (res) => {
              Toast.hide()
              if (res === 1) {
                let url = '/SignTheSuccess?result=' + PROCESS_STATUS.UNKOWN_SIGN_SUCCESS
                // router.push('/SignTheSuccess?result='+PROCESS_STATUS.UNKOWN_SIGN_SUCCESS);
                this.goNext(url)
              } else {
                let url = '/SignTheSuccess?result=' + PROCESS_STATUS.UNKOWN_SIGN_ERROR
                // router.push('/SignTheSuccess?result='+PROCESS_STATUS.UNKOWN_SIGN_ERROR)
                this.goNext(url)
              }
            }
          })
        }
        else {//表单数据为空
          //提示：还未添加任何表单，不允许签署
          let url = '/SignTheSuccess?result=' + PROCESS_STATUS.UNKOWN_SIGN_ERROR
          // router.push('/SignTheSuccess?result='+PROCESS_STATUS.UNKOWN_SIGN_ERROR)
          this.goNext(url)
          Toast.fail('还未添加任何表单，不允许签署')
        }
      }
    });
  }

  goNext = (url) => {
    localStorage.setItem("nextUrl", url)
    let { signCertificationResultsModel: { isSuccess, status } } = this.props;
    const isDingTalk = getIsDingTalk()
    if (isDingTalk === 'true') {
      //支付宝认证
      if (status === 'undefined' || status === '' || typeof (status) === 'undefined') {
        dingCloseWindow(isSuccess);
        return;
      }
    }
    router.push(url)
  }
  //页面跳转
  goBack = () => {
    clearInterval(this.timer)
    localStorage.setItem("nextUrl", '/Signature')
    let { signCertificationResultsModel: { isSuccess, status } } = this.props;
    const isDingTalk = getIsDingTalk()
    if (isDingTalk === 'true') {
      //支付宝认证
      if (status === 'undefined' || status === '' || typeof (status) === 'undefined') {
        localStorage.setItem('haveToAlipay', '')
        dingCloseWindow(isSuccess);
        return;
      }
    }
    let url = '/Signature'
    // localStorage.setItem('haveToAlipay','')
    router.push(url)
  };


  getHtml = (isSuccess, status, count) => {
    /**
     * 3个状态
     * 成功 失败 和 loading
     */
    const isDingTalk = getIsDingTalk()
    const contentContainer = commonStyles.result + ' ' + styles.resultContent
    return (
      <div className={contentContainer}>
        <div className={styles.IconImg}>
          {/*<div className={commonStyles.IconImg} style={{display: 'flex',alignItems: 'center'}}><div>身份验证通过</div></div>*/}
          {
            status == PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS || isSuccess === true || status == PROCESS_STATUS.PUSR_AUTHORIZING_SUCCESS ?
              ''
              :
              <div className={styles.IconImg}>
                {
                  status == PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR || isSuccess === false || status == PROCESS_STATUS.PUSR_AUTHORIZING_ERROR ?
                    <MyIcon type='iconClose' className={commonStyles.Icon + ' ' + styles.ErrorIcon} />
                    :
                    null
                }
              </div>
          }
        </div>
        {
          status == PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS || isSuccess === true || status == PROCESS_STATUS.PUSR_AUTHORIZING_SUCCESS ?
            ''
            :
            <>
              {
                status == PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR || isSuccess === false || status == PROCESS_STATUS.PUSR_AUTHORIZING_ERROR ?
                  <>
                    <div className={commonStyles.titleSuccess}><span>签署失败</span></div>
                    <div className={commonStyles.titleJump}><span>身份认证未通过</span></div>
                    <div className={'footerContainer' + ' ' + commonStyles.footerContainer}>
                      <Button type="primary" shape="round"
                        onClick={this.goBack}>
                        返回（{count}）
                      </Button>
                    </div>
                  </>
                  :
                  null
              }
            </>
        }
      </div>
    )
  }
  render() {
    const { signCertificationResultsModel: { isSuccess, status, count } } = this.props;
    return (
      <div className={styles.baseLayout}>
        {/*<MyNavBar title={"签署结果"} backUrl={'/Signature'} gobackStatus={true}/>*/}
        {
          status == PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR || isSuccess === false || status == PROCESS_STATUS.PUSR_AUTHORIZING_ERROR ? <MyNavBar title={"签署结果"} backUrl={'/Signature'} gobackStatus={true} /> : ''
        }
        {
          this.getHtml(isSuccess, status, count)
        }
      </div>
    )
  }
}

export default AuthenticationSuccess;
